﻿

namespace BM.Tools.WebControls.MForm.Controls
{
    using System.Collections.ObjectModel;
    using System.Xml;

    /// <summary>
    /// A collection of UriMapping objects
    /// </summary>
    public class UriMappings : Collection<UriMapping>
    {                
        /// <summary>
        /// Creates the UriMappings object from <see cref="XmlNamespaceManager" /> object
        /// </summary>
        /// <param name="manager">
        /// The manager.
        /// </param>
        /// <returns>
        /// the UriMappings object
        /// </returns>
        public static UriMappings FromManager(XmlNamespaceManager manager)
        {
            var uriMappings = new UriMappings();
            foreach (string key in manager)
            {
                if (key == "xml" || key == "xmlns")
                {
                    continue;
                }

                uriMappings.Add(new UriMapping(key, manager.LookupNamespace(key)));
            }

            return uriMappings;
        }

        /// <summary>
        /// Creates the <see cref="XmlNamespaceManager"/> object from the UriMappings
        /// </summary>
        /// <returns>
        /// the namespace manager
        /// </returns>
        public XmlNamespaceManager ToManager()
        {
            return ToManager(null);
        }

        /// <summary>
        /// Creates a namespace manager based on data rom the UriMappings obejct
        /// </summary>
        /// <param name="baseManager">
        /// The base manager.
        /// </param>
        /// <returns>
        /// the namespace manager
        /// </returns>
        public XmlNamespaceManager ToManager(XmlNamespaceManager baseManager)
        {
            var manager = CloneOrCreateEmptyManager(baseManager);                
            foreach (UriMapping mapping in this)
            {
                manager.AddNamespace(mapping.Prefix, mapping.Namespace);
            }

            return manager;
        }

        private static XmlNamespaceManager CloneOrCreateEmptyManager(XmlNamespaceManager baseManager)
        {
            var manager = new XmlNamespaceManager(new NameTable());
            if (baseManager != null)
            {
                foreach (var pair in baseManager.GetNamespacesInScope(XmlNamespaceScope.ExcludeXml))
                {
                    manager.AddNamespace(pair.Key, pair.Value);
                }
            }

            return manager;
        }
    }
}